package com.qf.flash.ui.chat;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qf.dblib.dao.impl.UserMgr;
import com.qf.flash.R;
import com.qf.flash.constant.FlashCodes;
import com.qf.flash.event.ChangeGroupEvent;
import com.qf.flash.http.response.BusinessInfoBean;
import com.qf.flash.http.response.PlayConditinoResponse;
import com.qf.flash.model.GroupDetailBean;
import com.qf.flash.model.ScriptRoomBean;
import com.qf.flash.mvp.contract.ChangeGroupContract;
import com.qf.flash.mvp.contract.ScriptContract;
import com.qf.flash.mvp.presenter.ChangeGroupPresenter;
import com.qf.flash.mvp.presenter.ScriptPrensenter;
import com.qf.flash.ui.home.ChoseBusinessActivity;
import com.qf.flash.ui.home.ScriptDetailActivity;
import com.qf.flash.ui.home.adapter.NumberItem;
import com.qf.flash.ui.home.adapter.ScriptRoomItem;
import com.qf.flash.ui.home.adapter.TypeItem;
import com.qf.flash.widget.GridSpaceItemDecoration;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.util.DateUtil;
import com.qf.flashlib.widget.ViewUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qf.flashlib.util.DateUtil.PATTERN_STANDARD16H;

/**
 * 2020/4/4 16:27
 * 改变组队信息
 */
public class ChangeGroupActivity extends BaseActivity implements ScriptContract.View, ChangeGroupContract.View {

    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.et_group_name)
    EditText etGroupName;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.rv_type)
    RecyclerView rvType;
    @BindView(R.id.rv_count)
    RecyclerView rvCount;
    @BindView(R.id.rv_hot)
    RecyclerView rvHot;
    @BindView(R.id.tv_sponsor)
    TextView tvSponsor;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.mRefresh)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.fl_theme)
    FrameLayout fl_theme;

    private RVAdapter<PlayConditinoResponse.ThemesBean> mTypeAdapter;
    private RVAdapter<String> mNumberAdapter;
    private RVAdapter<ScriptRoomBean> mHotAdapter;

    private GridLayoutManager hotManager;
    private int spanCount = 3;
    private GridSpaceItemDecoration decoration = new GridSpaceItemDecoration(spanCount, (int) (FlashLib.density * 14));
    private ScriptPrensenter mScriptPresenter;
    private ChangeGroupPresenter mChangePresenter;


    private TimePickerView mTimePicker;
    private Date mSelectDate;

    private GroupDetailBean groupDetailBean;
    private int pageNO = 1;
    private boolean isRefresh;

    //typeId	否	String	游戏类型id
    //name	否	String	剧本名称
    //theme	否	String	题材
    //num	否	Long	人数
    //isTop	否	String	是否是热门，0否，1是
    //money	否	Long	费用
    //pageNo	否	Integer	页数，默认从1开始
    //pageSize	否	Integer	每页多少条，默认30

    public static void start(Activity activity, GroupDetailBean bean) {
        Intent intent = new Intent(activity, ChangeGroupActivity.class);
        intent.putExtra("data", bean);
        activity.startActivity(intent);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_game;
    }

    @Override
    protected void initInject() {
        mScriptPresenter = new ScriptPrensenter();
        mChangePresenter = new ChangeGroupPresenter();
        initPresenters(mScriptPresenter, mChangePresenter);
    }

    @Override
    protected void initViewAndData() {
        groupDetailBean = (GroupDetailBean) getIntent().getSerializableExtra("data");
        if (groupDetailBean == null)
            return;
        tvTopTitle.setText("修改组队信息");
        initView();
        //初始化时间
        initTimeDialog();
        initRvType();
        initRvNumber();
        initRvHot();
        //不是狼人杀
        if (!FlashCodes.PLAY_WOLF_KILL.equals(groupDetailBean.getPlayType())) {
            initRefresh();
            mRefresh.autoRefresh();
        } else {
            fl_theme.setVisibility(View.GONE);
        }

        mScriptPresenter.getConditions(groupDetailBean.getPlayType(), "0");

    }

    private void initView() {
        etGroupName.setText(groupDetailBean.getTeamName());
        tvDate.setText(groupDetailBean.getGameTime());
        etPassword.setText(groupDetailBean.getGamePassword());
        tvShop.setText(groupDetailBean.getShopName());
    }

    private void initRefresh() {
        mRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                pageNO = 0;
                getPlayListHotData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                pageNO = 1;
                getPlayListHotData();
            }
        });
    }

    /**
     * 弹出选择时间
     */
    private void initTimeDialog() {
        //标题颜色
        int color = getResources().getColor(R.color.color_333333);
        //选中的时间
        Calendar selectedDate = Calendar.getInstance();
        if (mSelectDate != null)
            selectedDate.setTime(mSelectDate);
        //开始时间
        Calendar startDate = Calendar.getInstance();
        //结束时间
        Calendar endDate = Calendar.getInstance();
        endDate.set(2100, 11, 31);
        //构建选择器
        mTimePicker = new TimePickerBuilder(this, mTimeListener)
                .setType(new boolean[]{true, true, true, true, true, false})  // 默认全部显示
                .setOutSideCancelable(true)                                     //点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)                                                //是否循环滚动
                .setSubmitColor(color)                                          //确定按钮文字颜色
                .setCancelColor(color)                                          //取消按钮文字颜色
                .setDate(selectedDate)                                          // 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)
                .setLabel("年", "月", "日", "时", "分", "秒")                     //默认设置为年月日时分秒
                .isCenterLabel(false)                                            //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)                                                //是否显示为对话框样式
                .build();
    }

    /**
     * 选择时间监听
     */
    private OnTimeSelectListener mTimeListener = new OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            //记录时间
            mSelectDate = date;
            tvDate.setText(DateUtil.getDateToString(date.getTime(), PATTERN_STANDARD16H));
        }
    };

    private void getPlayListHotData() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("typeId", groupDetailBean.getPlayType());
        map.put("isTop", 0);
        map.put("pageNo", pageNO);
        mScriptPresenter.getPlayList(map);
    }

    private void getPlayListTypeData() {
        int typeChosenPosition = mTypeAdapter.getSingleChosenPosition();
        int numChosenPosition = mNumberAdapter.getSingleChosenPosition();

        HashMap<String, Object> map = new HashMap<>();
        map.put("typeId", groupDetailBean.getPlayType());
        map.put("isTop", 0);
        if (typeChosenPosition != -1) {
            map.put("theme", mTypeAdapter.getData(typeChosenPosition).getId());
        }
        if (numChosenPosition != -1) {
            map.put("num", mNumberAdapter.getData(numChosenPosition));
        }

        map.put("pageNo", 1);
        mScriptPresenter.getPlayList(map);
    }


    private void initRvHot() {
        hotManager = new GridLayoutManager(this, spanCount);
        rvHot.setLayoutManager(hotManager);
        rvHot.addItemDecoration(decoration);
        mHotAdapter = new RVAdapter<>(new ScriptRoomItem(this));
        rvHot.setAdapter(mHotAdapter);
        mHotAdapter.setOnItemClickListener((view, position) -> {
            ScriptDetailActivity.start(ChangeGroupActivity.this, mHotAdapter.getData(position).getId());
        });
        mHotAdapter.setOnItemChildClickListener((view, position) -> {
            mHotAdapter.setSingleChosenPosition(position);
            mHotAdapter.notifyDataSetChanged();
        });
    }


    private void initRvType() {
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvType.setLayoutManager(manager);
        mTypeAdapter = new RVAdapter<>(new TypeItem());
        rvType.setAdapter(mTypeAdapter);
        mTypeAdapter.setOnItemClickListener((view, position) -> {
            int singleChosenPosition = mTypeAdapter.getSingleChosenPosition();
            mTypeAdapter.setSingleChosenPosition(singleChosenPosition == position ? -1 : position);
            mTypeAdapter.notifyDataSetChanged();
            groupDetailBean.setPlayThemes(mTypeAdapter.getData(position).getId());
            getPlayListTypeData();

        });

    }

    private void initRvNumber() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvCount.setLayoutManager(manager);
        mNumberAdapter = new RVAdapter<>(new NumberItem());
        mNumberAdapter.setOnItemClickListener((view, position) -> {
            int singleChosenPosition = mNumberAdapter.getSingleChosenPosition();
            mNumberAdapter.setSingleChosenPosition(singleChosenPosition == position ? -1 : position);
            mNumberAdapter.notifyDataSetChanged();
            groupDetailBean.setNeedNum(mNumberAdapter.getData(position));
            getPlayListTypeData();
        });
        rvCount.setAdapter(mNumberAdapter);
    }


    private void udapeGame() {
        if (groupDetailBean == null)
            return;
        if (TextUtils.isEmpty(etGroupName.getText())) {
            FlashLib.showToast("请输入组队名称");
            return;
        }
        if (TextUtils.isEmpty(tvDate.getText())) {
            FlashLib.showToast("请选择时间");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("userId", UserMgr.getInstance().getLoginUser().getUid());
        map.put("groupId", groupDetailBean.getId());
        map.put("teamName", etGroupName.getText().toString());
        map.put("startTime", tvDate.getText().toString());
        map.put("password", etPassword.getText().toString());
        map.put("num", groupDetailBean.getNeedNum());
        int singleChosenPosition = mHotAdapter.getSingleChosenPosition();
        if (singleChosenPosition != -1)
            map.put("playId", mHotAdapter.getData(singleChosenPosition).getId());
        map.put("shopId", groupDetailBean.getShopId());
        mChangePresenter.changeGroup(map);

    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    @Subscribe
    public void choseShop(BusinessInfoBean bean) {
        if (groupDetailBean != null) {
            groupDetailBean.setShopId(bean.getId());
            tvShop.setText(bean.getShopName());
        }


    }

    @OnClick({R.id.tv_top_back, R.id.tv_date, R.id.tv_sponsor, R.id.tv_shop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.tv_date:
                if (mTimePicker != null) {
                    hideInput();
                    mTimePicker.show();
                }
                break;
            case R.id.tv_sponsor:
                udapeGame();
                break;
            case R.id.tv_shop:
                ChoseBusinessActivity.start(this, "",
                        groupDetailBean.getPlayType(),
                        groupDetailBean.getOrderId(),
                        "", true);
                break;
        }
    }

    @Override
    public void setPlayListData(List<ScriptRoomBean> data, int totalPage) {
        ViewUtil.setRefreshComplete(mRefresh,isRefresh);
        for (ScriptRoomBean datum : data) {
            datum.setSpanSize(3);
        }
        mHotAdapter.setSingleChosenPosition(-1);
        if (isRefresh) {
            mHotAdapter.setDatas(data);
        } else {
            mHotAdapter.addData(data);
        }
        mRefresh.setEnableLoadMore(pageNO < totalPage);
    }

    @Override
    public void setConditionData(PlayConditinoResponse response) {
        List<PlayConditinoResponse.ThemesBean> themes = response.getThemes();
        int themeSize = themes.size();
        for (int i = 0; i < themeSize; i++) {
            if (TextUtils.equals(themes.get(i).getId(), groupDetailBean.getPlayThemes())) {
                mTypeAdapter.setSingleChosenPosition(i);
            }
        }
        mTypeAdapter.setDatas(themes);
        List<String> nums = response.getNums();
        int size = nums.size();
        for (int i = 0; i < size; i++) {
            if (TextUtils.equals(groupDetailBean.getNeedNum() + "", nums.get(i))) {
                mNumberAdapter.setSingleChosenPosition(i);
                break;
            }
        }
        mNumberAdapter.setDatas(nums);
    }


    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    public void changSuccess() {
        EventBus.getDefault().post(new ChangeGroupEvent());
        FlashLib.showToast("修改组队信息成功");
        finish();
    }
}
